public class BinarySearchTree {
    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     * @param key
     */
    public boolean insert(int key) {
        if(root == null) {
            TreeNode node = new TreeNode(key);
            root = node;
        }else {
            TreeNode cur = root;
            TreeNode prev = null;
            while(cur != null) {
                prev = cur;
                if(cur.key < key){
                    cur = cur.right;
                }else if(cur.key > key){
                    cur = cur.left;
                }
            }
            TreeNode node = new TreeNode(key);
            if(key < prev.key) {
                prev.left = node;
            }else{
                prev.right = node;
            }
        }
        return true;
    }
    //查找key是否存在
    public TreeNode search(int key) {
        TreeNode cur = root;
        while(cur != null) {
            if(cur.key == key) {
                return cur;
            }else if(cur.key > key) {
                cur = cur.left;
            }else {
                cur = cur.right;
            }
        }
        return null;
    }
    //删除key的值
    public boolean remove(int key) {
        TreeNode cur = root;
        TreeNode prev = null;
        while(cur != null && cur.key != key) {
            prev = cur;
            if(cur.key < key) {
                cur =cur.right;
            }else if(cur.key > key) {
                cur = cur.left;
            }else{
                break;
            }

        }
        if(prev == null) {
            root = null;
            return false;
        }
        if(cur == null) {
            return false;
        }else{
            if(cur.left == null) {
                if(prev.left == cur) {
                    prev.left = cur.right;
                }else {
                    prev.right = cur.right;
                }
            }else if(cur.right == null){
                if(prev.left == cur) {
                    prev.left = cur.left;
                }else{
                    prev.right = cur.left;
                }
            }else{
                TreeNode tm = cur.right;
                TreeNode tmp = cur;
                while(tm.left != null) {
                    tmp = tm;
                    tm = tm.left;
                }
                if(tmp.right == tm){
                    tmp.right = tm.right;
                }else {
                    tmp.left = tm.right;
                }
                cur.key = tm.key;
            }
        }
        return true;
    }
}
